package com.zhentao.utils;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhentao.domain.vo.MapVo;
import com.zhentao.domain.vo.Result;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
public class MapXYUtils {
    final static String AK = "JQrQmCyTASKPkLnFqzR2W8kdRJqf1i5y";
    final static String ADDRESS_TO_LONGITUDEA_URL = "http://api.map.baidu.com/geocoding/v3/?output=json&location=showLocation";
    public static MapVo AddressToLongitude(String address) {
        if (StringUtils.isBlank(address)) {
            return null;
        }
        String url = ADDRESS_TO_LONGITUDEA_URL + "?output=json&ak=" + AK + "&address=" + address;
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        MapVo mapVo = new MapVo();
        try {
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            String html = EntityUtils.toString(entity);
            JSONObject jsonObject = JSONObject.parseObject(html);
            JSONObject resultObject = jsonObject.getJSONObject("result");
            JSONObject locationObject = resultObject.getJSONObject("location");
//            double lng = locationObject.getDouble("lng");
//            double lat = locationObject.getDouble("lat");
            double lng = new BigDecimal( locationObject.getDouble("lng")).setScale(6, BigDecimal.ROUND_DOWN).doubleValue();
            double lat = new BigDecimal(locationObject.getDouble("lat")).setScale(6, BigDecimal.ROUND_DOWN).doubleValue();
            mapVo.setNowX(lng);
            mapVo.setNowY(lat);
        } catch (Exception e) {
            return null;
        }

        return mapVo;
    }
}
